package cn.pink.core;

import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.MessageCodec;

import java.io.*;

/**
 * 分布式消息解码器
 * @Author: pink
 * @Date: 2021/12/10 17:44
 */
public class CallMessageCodec implements MessageCodec<Call, Call> {
    @Override
    public void encodeToWire(Buffer buffer, Call call) {
        final ByteArrayOutputStream b = new ByteArrayOutputStream();
        try (ObjectOutputStream o = new ObjectOutputStream(b)){
            o.writeObject(call);
            o.close();
            buffer.appendInt(b.toByteArray().length);
            buffer.appendBytes(b.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Call decodeFromWire(int pos, Buffer buffer) {
        int length = buffer.getInt(pos);
        final ByteArrayInputStream b = new ByteArrayInputStream(buffer.getBytes(pos + 4, pos + 4 + length));
        Call msg = null;
        try (ObjectInputStream o = new ObjectInputStream(b)){
            o.close();
            msg = (Call) o.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return msg;
    }

    @Override
    public Call transform(Call call) {
        return call;
    }

    @Override
    public String name() {
        return "call";
    }

    @Override
    public byte systemCodecID() {
        return -1;
    }
}
